﻿from django.db import models
from django.db.models.loading import get_app
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib import admin
from django import forms
from homesite.bugs import fields
from homesite.bugs import globals
from search import SearchManager







KIND_CHOICES = (
    ('Bug', 'Bug'),
    ('Feature', 'Feature'),
)

SEVERITY_CHOICES = (
    ('Dream', 'Dream'),
    ('Minor', 'Minor'),
    ('Normal', 'Normal'),
    ('Major', 'Major'),
)

STATUS_CHOICES = (
    ('New','New'),
    ('Open','Open'),
    ('In Progress','In Progress'),
    ('Resolved','Resolved'),

)

class Tag(models.Model):
  value = models.CharField(max_length=50)
  norm_value = models.CharField(max_length=50, editable=False)
  milestone = models.BooleanField(blank=True, default=False)
  sort = models.IntegerField(blank=True, default=10)
  
  class Meta:
    ordering=('norm_value','value')
  
  def __unicode__(self):
    return self.value
    
  def save(self):
    tags = get_app('bugs')
    from homesite.bugs.utils import normalize_title
    self.norm_value = normalize_title(self.value)
    super(Tag, self).save()
    
  def get_absolute_url(self):
    if getattr(settings, 'TAGS_URL', ''):
      from urllib import quote
      try:
        return settings.TAGS_URL % quote(self.value)
      except TypeError:
        return settings.TAGS_URL + quote(self.value)
    else:
      return reverse('homesite.bugs.views.tasktags', args=[globals.project_norm_name, self.value])


class ProjectCategory(models.Model):
    name = models.CharField(max_length=64, verbose_name='Категория')
  
    class Meta:
        ordering = ['name']
    
    def __unicode__(self):
        return self.name



class Project(models.Model):
    category = models.ForeignKey(ProjectCategory, blank=True, null=True, verbose_name='Категория')  
    name = models.CharField(max_length=64, verbose_name='Проект')
    norm_name = models.CharField(max_length=64, editable=False)
    description =  models.CharField(max_length=128, blank=True, verbose_name='Описание')
    url = models.URLField(verify_exists=True, blank=True)
    svnurl = models.URLField(verify_exists=True, blank=True)
    users = models.ManyToManyField(User)
  
    class Meta:
        ordering = ['name']
    
    def __unicode__(self):
        return self.name

    def save(self):
        from homesite.bugs.utils import normalize_title
        self.norm_name = normalize_title(self.name)
        super(Project, self).save()	


class Task(models.Model):
    serial = models.IntegerField(editable=False,verbose_name='Номер')
    project = models.ForeignKey(Project, verbose_name='Проект')
    kind = models.CharField(max_length=8, choices=KIND_CHOICES, verbose_name='Вид')  
    summary = models.CharField(max_length=100, verbose_name='Задача')
    description = models.TextField(blank=True, verbose_name='Описание')
    status =  models.CharField(max_length=16, choices=STATUS_CHOICES, verbose_name='Статус') 
    resolution = models.CharField(max_length=16, blank=True, verbose_name='') 
    reporter = models.ForeignKey(User, verbose_name='Создатель',related_name = 'task_reporter_set')
    owner = models.ForeignKey(User, verbose_name='Владелец',related_name = 'task_owner_set', default=None)
    severity = models.CharField(max_length=8, choices=SEVERITY_CHOICES, verbose_name='Severity', default=None) 
    severityorder = models.IntegerField(editable=False)
    reportdate = models.DateTimeField(auto_now_add=True, verbose_name='Дата')
    tags = fields.TagsField(Tag, blank=True)
    subscribers = models.ManyToManyField(User, blank=True, related_name = 'task_subscribers_set')
    
    objects = models.Manager()
    searches = SearchManager()
 
    class Meta:
        ordering = ['-severityorder', 'kind']
    
    def __unicode__(self):
        return self.summary		



class History(models.Model):
    task = models.ForeignKey(Task, verbose_name='Задача')
    action = models.TextField(editable=False, blank=True)
    comment = models.TextField(verbose_name='Коментарий', blank=True)
    date = models.DateTimeField(auto_now_add=True, verbose_name='Дата')
    user = models.ForeignKey(User, verbose_name='Пользователь')
    attachment = models.FileField(blank=True, upload_to='/upload')
    attachmentname = models.CharField(max_length=64, editable=False, blank=True)
    
    comment.allow_tags = True
    action.allow_tags = True

    class Meta:
        ordering = ['date']
    

    def __unicode__(self):
        return self.comment










admin.site.register(ProjectCategory)
admin.site.register(Project)
admin.site.register(Task)
admin.site.register(Tag)
admin.site.register(History)
